import { isFunctionalComponent } from './utils';
import mountElement from './mountElement';

/*
 * @author: yang long
 * @date: 2022-07-19 14:23:57
 * @description: 挂载 组件 方法
 * @virtualDOM {type}: 虚拟dom
 * @container {type}: 要挂载的 html 节点
 */
export default function mountComponent(virtualDOM, container, oldDOM) {
  let nextVirtualDOM = null;
  let component = null;
  if (isFunctionalComponent(virtualDOM)) {
    // 函数组件
    nextVirtualDOM = buildFunctionComponent(virtualDOM);
  } else {
    // 类组件
    nextVirtualDOM = buildClassComponent(virtualDOM);
    component = nextVirtualDOM.component;
  }

  // 去渲染组件，组件的返回值可能是jsx也可能又是一个组件
  mountElement(nextVirtualDOM, container, oldDOM);

  if (component) {
    component.componentDidMount();
    if (component.props && component.props.ref) {
      component.props.ref(component);
    }
  }
}

function buildFunctionComponent(virtualDOM) {
  return virtualDOM.type(virtualDOM.props || {});
}

function buildClassComponent(virtualDOM) {
  // type 存储的是构造函数
  const component = new virtualDOM.type(virtualDOM.props || {});
  const nextVirtualDOM = component.render();
  // 在这个里挂载 组件实例,方便后续 类组件 render
  nextVirtualDOM.component = component;
  return nextVirtualDOM;
}
